<script setup>
import { useMouseInElement } from '@vueuse/core';
import { ref, watch, defineProps } from 'vue';

// 接受父组件参数
const props = defineProps({
  imageList: {
    type: Array,
    default: () => []
  }
})


// 大图下标
const bigIndex = ref(0)

// 鼠标移入小图
const enterHandle = (index) => {
    bigIndex.value = index
}

// 大图片盒子对象
const target = ref(null)

// 蒙版位置
const maskStyle = ref({
    left: 0,
    top: 0
})

// 获取鼠标在大盒子内部位置
const { elementX, elementY, isOutside} = useMouseInElement(target)

// 监听鼠标位置变化
watch(()=> {
    // 横向位置
    if (!isOutside.value) {
        if (elementX.value > 100 && elementX.value < 300) {
        maskStyle.value.left = elementX.value - 100
    }
    if (elementY.value > 100 && elementY.value < 300) {
        maskStyle.value.top = elementY.value - 100
    }

    // 边界位置
    if (elementX.value <= 100) 
        maskStyle.value.left = 0
    if (elementX.value >= 300)
        maskStyle.value.left = 200
    if (elementY.value <= 100)
        maskStyle.value.top = 0
    if (elementY.value >= 300)  
        maskStyle.value.top = 200
    }
})


</script>


<template>
  <div class="goods-image">
    <!-- 左侧大图-->
    <div class="middle" ref="target">
      <img :src="props.imageList[bigIndex]" alt="" />
      <!-- 蒙层小滑块 -->
      <div v-if="!isOutside" class="layer" :style="{ left: `${maskStyle.left}px`, top: `${maskStyle.top}px` }"></div>
    </div>
    <!-- 小图列表 -->
    <ul class="small">
      <li v-for="(img, i) in props.imageList" :class="{active: i === bigIndex}" :key="i" @mouseenter="enterHandle(i)">
        <img :src="img" alt="" />
      </li>
    </ul>
    <!-- 放大镜大图 -->
    <div class="large" :style="[
      {
        backgroundImage: `url(${props.imageList[bigIndex]})`,
        backgroundPositionX: `${-2 * maskStyle.left}px`,
        backgroundPositionY: `${-2 * maskStyle.top}px`,
      },
    ]" v-show="!isOutside"></div>
  </div>
</template>

<style scoped lang="scss">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;

  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
  }

  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index: 500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    // 背景图:盒子的大小 = 2:1  将来控制背景图的移动来实现放大的效果查看 background-position
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }

  .layer {
    width: 200px;
    height: 200px;
    background: rgba(0, 0, 0, 0.2);
    // 绝对定位 然后跟随咱们鼠标控制left和top属性就可以让滑块移动起来
    left: 0;
    top: 0;
    position: absolute;
  }

  .small {
    width: 80px;

    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;

      &:hover,
      &.active {
        border: 2px solid $xtxColor;
      }
    }
  }
}
</style>